package com.canyou.common;

import com.canyou.captcha.KaptchaConfig;
import com.canyou.enums.ErrorCodeEnum;
import com.canyou.exception.CysBusinessException;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码生成控制器
 *
 * @author fy
 * @date 19/12/11 13:58
 */
@Api(tags = "图形验证码管理")
@Controller
@RequestMapping("/captcha")
@Validated
public class CaptchaController {

    @Autowired
    private Producer producer;

    @ApiOperation(value = "获取验证码")
    @ApiImplicitParam(name = "generate_key", paramType = "path", value = "验证码键generate_key",
            dataType = "string", required = true, example = "faf6ac9b-d915-441f-8f71-9ede9ae43c2c")
    @GetMapping("/index/{generate_key}")
    public void createCaptcha(@NotBlank(message = "generate_key不能为空")
                              @PathVariable(name = "generate_key") String generateKey,
                              HttpServletResponse response) {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String code = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(code);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "JPEG", out);
            // 缓存验证码
            KaptchaConfig.cacheKaptcha(generateKey, code);
        } catch (IOException e) {
            throw new CysBusinessException(ErrorCodeEnum.ILLEGAL, "生成二维码出错", e);
        }
    }

}
